package com.nache.ws;

import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.util.Log;

import com.nache.reps.ItemCategory;
import com.nache.reps.MenuItem;

public class RestAPICall {
	public static ArrayList<ItemCategory> getItemCategories() {
		ArrayList<ItemCategory> ilist = new ArrayList<ItemCategory>();
		NetworkCallAsync ncall = new NetworkCallAsync();
		String result = null;
		ncall.execute("http://easyordersg99.cloudfoundry.com/api/itemCategory");
		try {
			result = ncall.get();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (result != null) {
			try {
				JSONArray arr = new JSONArray(result);
				for (int i = 0; i < arr.length(); i++) {
					JSONObject curobj = arr.getJSONObject(i);

					int parentid = -1;
					if(!curobj.getString("parent").equals("null")){
						parentid = ((JSONObject) curobj.get("parent"))
								.getInt("id");
					}
					ItemCategory temp = new ItemCategory(curobj.getInt("id"), curobj
							.getString("catName"), parentid, curobj
									.getString("lastUpdated"),
							curobj.getString("dateCreated"),((JSONObject) curobj.get("outlet"))
									.getInt("id"));
					ilist.add(temp);
					Log.i("myobjects",temp.toString());

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return ilist;
	}

	public static ArrayList<MenuItem> getMenuItems(int catid) {
		return null;
	}

	public static ArrayList<MenuItem> getMenuItems() {
		ArrayList<MenuItem> ilist = new ArrayList<MenuItem>();
		NetworkCallAsync ncall = new NetworkCallAsync();
		String result = null;
		ncall.execute("http://easyordersg99.cloudfoundry.com/api/menuItem");
		try {
			result = ncall.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (result != null) {
			try {
				JSONArray arr = new JSONArray(result);
				for (int i = 0; i < arr.length(); i++) {
					JSONObject curobj = arr.getJSONObject(i);
					MenuItem temp = new MenuItem(curobj.getInt("id"), curobj
							.getString("itemName"), "URL-missing", curobj
							.getString("itemdesc"), curobj.getDouble("price"),
							curobj.getString("currency"), curobj
									.getString("dateCreated"),curobj
									.getString("lastUpdated"),
							((JSONObject) curobj.get("itemCategory"))
									.getInt("id"));
					ilist.add(temp);
					
					Log.i("myobjects",temp.toString());

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return ilist;
	}

}
